package com.i2863.receipt.interceptor;

import com.i2863.receipt.controller.ApiStatus;
import com.i2863.receipt.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

/**
 * controller error handler
 *
 * @author xuweiwei
 * @date 2018/5/7
 */
@ControllerAdvice(basePackages = ("com.i2863.receipt.controller"))
public class ExceptionReaper {

    private static Logger logger = LoggerFactory.getLogger(ExceptionReaper.class);

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Object exception(Exception exception, WebRequest request) {
        String url = ((ServletWebRequest) request).getRequest().getServletPath();
        logger.info("Catch an exception,url:{}", url, exception);
        if (url.contains("/api")) {
            if (exception instanceof ServiceException) {
                ServiceException e = (ServiceException) exception;
                ApiStatus apiStatus = e.getApiStatus();
                if (apiStatus != null) {
                    return apiStatus.toMap();
                }
            }
            return ApiStatus.ERROR.toMap();
        } else {
            return "<html><head><meta http-equiv=\"refresh\" content=\"1;url=/500.html\">   </head></html>";
        }

    }

}
